import React, { Component } from 'react';
import { Button, Card, Icon, Spin, Tooltip } from 'antd';
import styles from './index.less';
import SearchForm from './SearchForm';
import { connect } from 'dva';
import ProTable from '@ant-design/pro-table';
import BaseComponent from '@/components/BaseComponent';
import DetailView from '@/pages/DataMerger/InitialDataReportingFlib/DetailView';
import { saveAs } from 'file-saver';

@connect(({ user, initialdatareporting, loading }) => ({
  currentUser: user.currentUser,
  data: initialdatareporting.data2,
  isPreparing: loading.effects['initialdatareporting/listAllTableColumn4Office'],
  isFinding: loading.effects['initialdatareporting/findDataById'],
  isLoading: loading.effects['initialdatareporting/getPageData'],
}))
class InitialDataReportingFlib extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 被选中的行
      selectedRows: [],
      // columns
      tableColumns: [],
      // 默认将被取消选中的column
      columnsStateMap: {},
      // 食管病理诊断代码
      sgblCode: [],
      // 是否活检
      isHj: [],
      // 十二指肠病理诊断代码
      sezccode: [],
      // 是否无痛
      ache: [],
      // 对象来源
      zldxLy: [],
      // 染色类别
      dye: [],
      // Hp检测结果
      Hp: [],
      // Hp检测方法
      hpjcjg: [],
      // 贲门病理诊断代码
      bmblCode: [],
      // 胃病理诊断代码
      wblCode: [],
      //性别
      xbcode: [],
      // 诊疗方式
      zlFs: [],
      //是否有错误
      isHaveError: [],
      // 被选中的记录
      record: {},
      // 编辑视图的显示状态
      detailViewVisible: false,
      // 是否是管理员
      isAdmin: false,
      //城市集合
      cities: [],
      //区县街道集合
      districtAndStreet: [],
    };
  }

  componentDidMount() {
    const { roles: currentRoles } = this.props.currentUser;
    // 检查是否包含ROLE_ADMIN
    const isAdmin = this.checkIsAdmin(this.props.currentUser);
    this.setState({ isAdmin });
    if (isAdmin) {
      // 读取城市
      this.getAllCities().then(list => {
        if (list) {
          this.setState({ cities: list },()=>{
            this.searchform.loadCompleted();
          });
          if (list[0]) {
            this.getDistrictAndStreet(list[0].id);
          }
        }
      });
    }
    this.listAllTableColumn4Office();
  }

  listAllTableColumn4Office = () => {
    this.execHttp('initialdatareporting/listAllTableColumn4Office', {}).then(resp => {
      const {
        success,
        data: { colums },
      } = resp;
      let tableColumns = [];
      if (success) {
        tableColumns = colums;
      }
      this.setState(
        {
          tableColumns,
        },
        () => {
          this.initColumnsStateMap();
          this.getPageData();
          this.dictListAllByCode();
        }
      );
    });
  };

  /**点击获取省下面的城市*/
  getAllCities = () => {
    return new Promise((resolve, reject) => {
      this.execHttp('orgsetting/getAllProvinceCity', {
        parentRegionCode: '340000',
        user: this.props.currentUser.id,
      }).then(resp => {
        if (resp && resp.success) {
          const {
            success,
            data: { list },
          } = resp;
          if (success) {
            return resolve(list);
          }
        }
      });
    });
  };

  /**获取城市下的区街道信息*/
  getDistrictAndStreet = val => {
    this.execHttp('orgsetting/getDistrictAndStreet', {
      parentRegionCode: val,
    }).then(resp => {
      if (resp && resp.success) {
        const { success, data } = resp;
        if (success) {
          this.setState({
            districtAndStreet: data.list,
          });
        }
      }
    });
  };

  //初始化columnsStateMap
  initColumnsStateMap = () => {
    const { tableColumns } = this.state;
    const tmp = tableColumns.filter(item => item.fieldShow === 1);
    const columnsStateMap = {};
    tmp.forEach(item => {
      columnsStateMap[item.fieldName] = { show: false };
    });
    this.setState({
      columnsStateMap: { ...columnsStateMap },
    });
  };

  getColumns = () => {
    const { tableColumns } = this.state;
    const colums = tableColumns.map((item, index) => {
      const { fieldLabel, fieldName, fieldWidth } = item;
      if (fieldName === 'qualified_status') {
        return {
          title: fieldLabel,
          dataIndex: fieldName,
          fixed: 'left',
          width: 120,
          render: (text, record, index) => {
            const { is_have_error, error_message } = record;
            if (is_have_error === 0) {
              return <div className={styles.successBox}>合格</div>;
            } else if (is_have_error === 1) {
              const arr = error_message ? error_message.split('|') : [];
              const msg = arr.map((item, index) => {
                return (
                  <div key={index}>
                    `${index + 1}.${item}`
                  </div>
                );
              });
              return (
                <div className={styles.errorBox}>
                  <span>不合格</span>
                  <Tooltip placement="top" title={<div>{msg}</div>}>
                    <Icon type="exclamation-circle" style={{ marginTop: '2px' }} />
                  </Tooltip>
                </div>
              );
            }
          },
        };
      } else {
        return {
          title: fieldLabel,
          dataIndex: fieldName,
          key: fieldName,
          width: fieldWidth > 0 ? fieldWidth : 200,
        };
      }
    });
    return [
      ...colums,
      {
        title: '操作',
        key: 'operateCol',
        width: 100,
        fixed: 'right',
        render: (text, record, index) => {
          return (
            <div>
              <Button
                type="primary"
                size={'small'}
                style={{ marginRight: '8px' }}
                onClick={() => {
                  this.detailBtn(record);
                }}
              >
                详情
              </Button>
            </div>
          );
        },
      },
    ];
  };

  /**
   * 获取所有列表数据
   * */
  getPageData = params => {
    this.execHttp('initialdatareporting/getPageData', {
      user: this.props.currentUser.id,
      currentPage: 1,
      pageSize: 10,
      ...params,
    });
  };

  /**
   * 字典接口
   * */
  dictListAllByCode = () => {
    this.execHttp('cersysdict/dictListAllByCode', {}).then(resp => {
      const { success, data } = resp;
      if (success) {
        this.setState({
          //食管病理诊断代码
          sgblCode: data.sgbl_code,
          //是否活检
          isHj: data.is_hj,
          //十二指肠病理诊断代码
          sezccode: data.sezc_code,
          //是否无痛
          ache: data.ache,
          //对象来源
          zldxLy: data.zldx_ly,
          //染色类别
          dye: data.dye,
          //Hp检测结果
          Hp: data.Hp,
          //Hp检测方法
          hpjcjg: data.hpjcjg,
          //贲门病理诊断代码
          bmblCode: data.bmbl_code,
          //胃病理诊断代码
          wblCode: data.wbl_code,
          //性别
          xbcode: data.xb_code,
          // 诊疗方式
          zlFs: data.zl_fs,
          //是否有错误
          isHaveError: data.is_have_error,
          //tag1
          tag1: data.tag1,
          //tag2
          tag2: data.tag2,
          //tag3
          tag3: data.tag3,
          //tag4
          tag4: data.tag4,
          //tag5
          tag5: data.tag5,
        });
      }
    });
  };

  /**
   * 根据id获取详细信息
   * @param id
   */
  findById = ({ id }) => {
    if (this.props.isFinding) {
      return;
    }
    const hide = this.loadingMessage('操作中,请稍后...');
    this.execHttp('initialdatareporting/findDataById', { id })
      .then(resp => {
        hide();
        const {
          success,
          message,
          data: { response },
        } = resp;
        if (success) {
          this.setState({
            record: response,
            detailViewVisible: true,
          });
        } else {
          this.errorMessage(message);
        }
      })
      .catch(error => {
        hide();
      });
  };

  /**
   * 查询按钮
   * */
  searchBtn = data => {
    let { njzl_time, insert_datetime, blbgTime, ...others } = data;
    let insertStart;
    let insertEnd;
    let njzlStart;
    let njzlEnd;
    let blbgDate;

    let params = { ...others };

    if (blbgTime) {
      blbgDate = blbgTime.format('YYYY-MM-DD');
      params['blbgDate'] = blbgDate;
    }

    // 内镜诊疗日期范围
    if (njzl_time && njzl_time.length == 2) {
      njzlStart = njzl_time[0].format('YYYY-MM-DD');
      njzlEnd = njzl_time[1].format('YYYY-MM-DD');
      params['njzlStart'] = njzlStart;
      params['njzlEnd'] = njzlEnd;
    }

    // 创建时间日期范围
    if (insert_datetime && insert_datetime.length == 2) {
      insertStart = insert_datetime[0].format('YYYY-MM-DD');
      insertEnd = insert_datetime[1].format('YYYY-MM-DD');
      params['insertStart'] = insertStart;
      params['insertEnd'] = insertEnd;
    }

    // console.log(`查询内容:${JSON.stringify(params)}`);

    this.clearAllSelectedRows().then(() => {
      this.getPageData(params);
    });
  };

  /**
   * 重置选中
   */
  clearAllSelectedRows = () => {
    return new Promise(resolve => {
      this.setState(
        {
          selectedRows: [],
          selectedRowKeys: [],
        },
        () => {
          resolve();
        }
      );
    });
  };

  /**
   * 重置按钮
   * */
  resetBtn = () => {
    this.clearAllSelectedRows().then(() => {
      this.getPageData();
    });
  };

  /**
   * 点击详情按钮
   * @param record
   */
  detailBtn = record => {
    this.findById({ id: record.id });
  };

  /**
   * 点击关闭抽屉
   */
  closeBtn = () => {
    this.setState({
      detailViewVisible: false,
    });
  };

  /**
   * 点击导出按钮
   */
  onExportClick = () => {
    const {
      data: { list },
    } = this.props;
    let ids = [];
    list.map((item, index) => {
      ids.push(item.id);
    });
    let str = '';
    ids.map((item, index) => {
      str += `${item}|`;
    });
    if (this.props.isExporting) {
      return;
    }
    const hide = this.loadingMessage('正在导出数据,请稍后...');
    this.execHttp('initialdatareporting/queryAllExportData', {
      user: this.props.currentUser.id,
      ids: str,
    })
      .then(response => {
        hide();
        saveAs(response, '初始数据正式库上报' + '.xlsx');
      })
      .catch(error => {
        hide();
      });
  };

  handleBasicTableChange = () => {};

  render() {
    const { data } = this.props;
    const { selectedRows, isAdmin } = this.state;
    return (
      <div className={styles.initialDataReportingFlib}>
        <Card bordered={true} title={'初始数据正式库'}>
          <SearchForm
            wrappedComponentRef={searchform => (this.searchform = searchform)}
            dictSex={this.state.xbcode}
            isAdmin={this.state.isAdmin}
            cities={this.state.cities}
            districtAndStreet={this.state.districtAndStreet}
            searchBtn={this.searchBtn}
            resetBtn={this.resetBtn}
            onExportClick={this.onExportClick}
            onCityChange={this.handleOnCityChange}
          ></SearchForm>
        </Card>
        <Card bordered={true} className={styles.contentBox}>
          {this.props.isPreparing ? (
            <div className={styles.spinBox}>
              <Spin />
            </div>
          ) : (
            <ProTable
              data={data}
              bordered={true}
              search={false}
              rowKey={record => record.id}
              // selectedRows={selectedRows}
              loading={this.props.isLoading}
              dataSource={data ? data.list : []}
              pagination={data ? data.pagination : {}}
              columnsStateMap={this.state.columnsStateMap}
              onColumnsStateChange={map => {
                if (Object.keys(map).length > 0) {
                  this.setState({
                    columnsStateMap: map,
                  });
                } else {
                  this.initColumnsStateMap();
                }
              }}
              columns={this.getColumns()}
              onChange={this.handleBasicTableChange}
              options={{
                density: false,
                reload: false,
                fullScreen: false,
                setting: true,
              }}
              scroll={{ x: true }}
            />
          )}
        </Card>
        {/*详情*/}
        {this.state.detailViewVisible ? (
          <DetailView
            onClose={this.closeBtn}
            visible={this.state.detailViewVisible}
            record={this.state.record}
            sgblCode={this.state.sgblCode}
            isHj={this.state.isHj}
            sezccode={this.state.sezccode}
            ache={this.state.ache}
            zldxLy={this.state.zldxLy}
            dye={this.state.dye}
            Hp={this.state.Hp}
            hpjcjg={this.state.hpjcjg}
            bmblCode={this.state.bmblCode}
            wblCode={this.state.wblCode}
            xbcode={this.state.xbcode}
            zlFs={this.state.zlFs}
            tag1={this.state.tag1}
            tag2={this.state.tag2}
            tag3={this.state.tag3}
            tag4={this.state.tag4}
            tag5={this.state.tag5}
            isHaveError={this.state.isHaveError}
          ></DetailView>
        ) : null}
      </div>
    );
  }

  /**
   * 处理城市改变
   * @param value
   */
  handleOnCityChange = value => {
    if (value !== undefined) {
      this.getDistrictAndStreet(value);
    } else {
      this.setState({
        districtAndStreet: [],
      });
    }
  };
}

export default InitialDataReportingFlib;
